package com.insigma.business.common.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.insigma.business.common.dto.CurrentUser;
import com.insigma.business.common.dto.WxRegisterInfo;
import com.insigma.business.common.service.DfsService;
import com.insigma.business.common.service.LocalLoginService;
import com.insigma.business.common.service.WechatService;
import com.insigma.business.common.utils.PriInfoHandleUtil;
import com.insigma.business.qrcode.common.dao.SoldierBasicInfoBDao;
import com.insigma.business.qrcode.common.dto.ErrorCodeEnum;
import com.insigma.business.qrcode.common.dto.LoginUserTypeEnum;
import com.insigma.business.qrcode.common.dto.search.SoldierBasicInfoBSearch;
import com.insigma.business.qrcode.common.entity.SoldierBasicInfoB;
import com.insigma.business.qrcode.common.service.SequenceGenerator;
import com.insigma.business.qrcode.common.util.BizException;
import com.insigma.business.qrcode.common.util.CommonConstant;
import com.insigma.business.qrcode.common.vo.UserTypeEnum;
import com.insigma.business.qrcode.soldier.dao.SoldierOuterLoginAccountDao;
import com.insigma.business.qrcode.soldier.dto.SequenceNameConstant;
import com.insigma.business.qrcode.soldier.entity.SoldierApplyInfoDO;
import com.insigma.business.qrcode.soldier.entity.SoldierBasicInfoDO;
import com.insigma.business.qrcode.soldier.entity.SoldierOuterLoginAccountDO;
import com.insigma.business.qrcode.soldier.service.SoldierApplyInfoService;
import com.insigma.business.qrcode.soldier.service.SoldierBasicInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class LocalLoginServiceImpl implements LocalLoginService {
    @Autowired(required = false)
    private SequenceGenerator sequenceGenerator;

    @Resource
    private SoldierBasicInfoService soldierBasicInfoService;

    @Resource
    private SoldierOuterLoginAccountDao soldierOuterLoginAccountDao;

    @Resource
    private DfsService dfsService;

    @Resource
    private SoldierApplyInfoService soldierApplyInfoService;

    @Resource
    private WechatService wechatService;


    @Override
    public CurrentUser getSoldierInfoByOpenid(String openid) {
        if (StringUtils.isEmpty(openid)) {
            throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR,"未获取到openid");
        }
        CurrentUser ret = new CurrentUser();
        ret.setWechatOpenid(openid);
        //查询第三方登录信息
        SoldierOuterLoginAccountDO qSoldierOuterLoginAccountDO = new SoldierOuterLoginAccountDO();
        qSoldierOuterLoginAccountDO.setOuterSysType(CommonConstant.OUTER_SYS_TYPE_WX_1);
        qSoldierOuterLoginAccountDO.setOuterSysAccountId(openid);
        List<SoldierOuterLoginAccountDO> soldierOuterLoginAccountList = soldierOuterLoginAccountDao.querySoldierOuterLoginAccountList(qSoldierOuterLoginAccountDO);
        //判断有无第三方登录信息
        if (CollectionUtil.isEmpty(soldierOuterLoginAccountList)) {
            ret.setCasualUserFlag(true);
            ret.setLoginUserType(LoginUserTypeEnum.UNREGISTERED.name());
        } else {
            ret.setLoginUserType(LoginUserTypeEnum.GUESTS_COMM.name());
            SoldierOuterLoginAccountDO soldierOuterLoginAccountDO = soldierOuterLoginAccountList.get(0);
            ret.setProfilePicture(soldierOuterLoginAccountDO.getOuterSysAvatarUrl());
            ret.setMobile(PriInfoHandleUtil.decrypt(soldierOuterLoginAccountDO.getOuterSysMobile()));
            // 通过手机号查询申领信息（本人或者代申领人）
            List<SoldierApplyInfoDO> applyInfoList = soldierApplyInfoService.getByMobile(soldierOuterLoginAccountDO.getOuterSysMobile());
            if (CollectionUtil.isNotEmpty(applyInfoList)) {
                SoldierApplyInfoDO applyInfoDO = applyInfoList.get(0);
                BeanUtils.copyProperties(applyInfoDO,ret);
                ret.setAdmdvs(applyInfoDO.getServiceStationAdminArea());
                ret.setMobile(PriInfoHandleUtil.decrypt(applyInfoDO.getMobile()));
                ret.setIdCardNo(PriInfoHandleUtil.decrypt(applyInfoDO.getIdCardNo()));
                ret.setSoldierType(applyInfoDO.getSoldierType());
                if (StringUtils.equals(soldierOuterLoginAccountDO.getOuterSysMobile(),applyInfoDO.getMobile())) {
                    ret.setLoginUserType(LoginUserTypeEnum.OWN.name());
                } else {
                    ret.setLoginUserType(LoginUserTypeEnum.PROXY.name());
                }
            } else { // 未申领人员
                SoldierBasicInfoDO soldierBasicInfoDO = soldierBasicInfoService.getByMobile(soldierOuterLoginAccountDO.getOuterSysMobile());
                if (ObjectUtil.isNotEmpty(soldierBasicInfoDO)) {
                    ret.setLoginUserType(LoginUserTypeEnum.GUESTS_SOLDIER.name());
                    BeanUtils.copyProperties(soldierBasicInfoDO,ret);
                    ret.setAdmdvs(soldierBasicInfoDO.getServiceStationAdminArea());
                    ret.setMobile(PriInfoHandleUtil.decrypt(soldierBasicInfoDO.getMobile()));
                    ret.setIdCardNo(PriInfoHandleUtil.decrypt(soldierBasicInfoDO.getIdCardNo()));
                    ret.setSoldierType(soldierBasicInfoDO.getSoldierType());
                }
            }
        }
        return ret;
    }

    @Override
    public CurrentUser register(WxRegisterInfo wxRegisterInfo) {
        JSONObject jsonObject = wechatService.getPhoneNumber(wxRegisterInfo.getMobile());
        wxRegisterInfo.setMobile(jsonObject.getJSONObject("phone_info").getString("purePhoneNumber"));
        SoldierOuterLoginAccountDO insert = buildSoldierOuterLoginAccountDOForRegister(wxRegisterInfo);
//        SoldierBasicInfoBSearch search1 = new SoldierBasicInfoBSearch();
//        search1.setMobile(PriInfoHandleUtil.encrypt(wxRegisterInfo.getMobile()));
//        List<SoldierBasicInfoB> soldierBasicInfoBs = soldierBasicInfoBDao.search(search1);
        SoldierBasicInfoDO soldierBasicInfoDO = soldierBasicInfoService.getByMobile(PriInfoHandleUtil.encrypt(wxRegisterInfo.getMobile()));
        if (ObjectUtil.isNotEmpty(soldierBasicInfoDO)) {
            insert.setSoldierId(soldierBasicInfoDO.getSoldierId());
        }
        soldierOuterLoginAccountDao.insert(insert);
        CurrentUser currentUser = getSoldierInfoByOpenid(wxRegisterInfo.getOpenid());
        return currentUser;
    }


    private SoldierOuterLoginAccountDO buildSoldierOuterLoginAccountDOForRegister(final WxRegisterInfo wxRegisterInfo) {
        SoldierOuterLoginAccountDO soldierOuterLoginAccountDO = new SoldierOuterLoginAccountDO();
        soldierOuterLoginAccountDO.setId(sequenceGenerator.genKey(SequenceNameConstant.SOLDIER_OUTER_LOGIN_ACCOUNT_ID));
        soldierOuterLoginAccountDO.setSoldierId("");
        soldierOuterLoginAccountDO.setOuterSysType(1);
        soldierOuterLoginAccountDO.setOuterSysAccountId(wxRegisterInfo.getOpenid());
        soldierOuterLoginAccountDO.setOuterSysNickName(wxRegisterInfo.getNickName());
        soldierOuterLoginAccountDO.setOuterSysMobile(PriInfoHandleUtil.encrypt(wxRegisterInfo.getMobile()));
        soldierOuterLoginAccountDO.setOuterSysAvatarUrl(wxRegisterInfo.getProfilePicture());
        soldierOuterLoginAccountDO.setOuterStatus("1");
        soldierOuterLoginAccountDO.setEnabled(true);
        soldierOuterLoginAccountDO.setCreateDatetime(new Date());
        soldierOuterLoginAccountDO.setCreatorId(wxRegisterInfo.getOpenid());
        soldierOuterLoginAccountDO.setCreatorType(UserTypeEnum.OPEN.name());
        soldierOuterLoginAccountDO.setModifyDatetime(new Date());
        soldierOuterLoginAccountDO.setModifierId(wxRegisterInfo.getOpenid());
        soldierOuterLoginAccountDO.setModifierType(UserTypeEnum.OPEN.name());
        soldierOuterLoginAccountDO.setDeleted(false);
        return soldierOuterLoginAccountDO;
    }
}
